/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.device.modular.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.xiaonuo.device.core.enums.Constants;
import vip.xiaonuo.device.core.enums.DeviceErrEnum;
import vip.xiaonuo.device.modular.entity.ApiLog;
import vip.xiaonuo.device.modular.entity.BizCabinetDoor;
import vip.xiaonuo.device.modular.entity.SysUser;
import vip.xiaonuo.device.modular.mapper.CabinetDoorMapper;
import vip.xiaonuo.device.modular.mapper.UserMapper;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 设备api日志Service接口实现类
 *
 * @author levin
 * @date 2022/11/30 13:27
 **/
@Service("deviceDoorOpenService")
public class DeviceDoorOpenServiceImpl extends DeviceBaseService {
    @Autowired
    private UserMapper userMapper;

    @Override
    protected Integer getReqType() {
        return Constants.OPENDOOR;
    }

    @Resource
    private CabinetDoorMapper cabinetDoorMapper;

    @Override
    protected void handleLog(ApiLog log, JSONObject param) {
        JSONObject data = param.getJSONObject("data");
        String cabinetCode = data.getString("cabinetcode");
        String doorcode = data.getString("doorcode");
        List<String> opener = data.getObject("opener", List.class);
        List<String> rfids = data.getObject("rfids", List.class);

        log.setCabinetCode(cabinetCode);
        log.setCabinetDoorCode(doorcode);

        log.setRfids(String.join(",", rfids));

        if (CollectionUtil.isNotEmpty(opener)) {
            String userId = CollectionUtil.getLast(opener);
            log.setUserId(userId);
            SysUser userInfo = userMapper.selectById(userId);
            Assert.notNull(userInfo,"对应用户不存在");
            log.setUserNo(userInfo.getUserNo());
            if (opener.size() > 1) {
                //第一个作为管理员ID
                log.setAdminId(opener.get(0));
            }
        }
        ApiLog latestCloseDoor = apiLogMapper.getLatestCloseDoor(cabinetCode,doorcode);
        //默认不对称
        log.setPariFlag(0);
        if (latestCloseDoor != null) {
            //区间集合-上一次关门
            List<ApiLog> relatedList = apiLogMapper.getDoorRelatedList(cabinetCode, doorcode, latestCloseDoor.getEventTime(), log.getEventTime());
            if (CollectionUtil.isNotEmpty(relatedList)) {
                log.setRelationIds(relatedList.stream().map(ApiLog::getId).collect(Collectors.joining(",")));
                List<ApiLog> openLog = relatedList.stream().filter(apilog -> apilog.getReqType() == Constants.OPENDOOR).collect(Collectors.toList());
                if (openLog.size() == 0) {
                    //配对-无开门记录
                    log.setRelationId(latestCloseDoor.getId());
                    log.setPariFlag(1);
                } else {
                    //补偿机制【时间一样情况】
                    if(openLog.get(openLog.size() - 1).getEventTime().equals(latestCloseDoor.getEventTime())){
                        //配对-无开门记录
                        log.setRelationId(latestCloseDoor.getId());
                        log.setPariFlag(1);
                    }else{
                        //非配对-有开门记录
                        log.setRelationId(openLog.get(openLog.size() - 1).getId());
                    }
                }
            }
        }
        //获取柜门信息
        BizCabinetDoor cabinetDoor = cabinetDoorMapper.getInfoByCodes(cabinetCode, doorcode);
        log.setActCompTime(cabinetDoor.getActTime());
        //更新柜门动作时间
        int count = cabinetDoorMapper.updateActTime(cabinetDoor.getId(),log.getEventTime());
        if(count==0){
            log.setResulltType(DeviceErrEnum.REQ_ACT_TIMEOUT.getValue());
        }else{
            log.setResulltType(DeviceErrEnum.SUCCESS.getValue());
        }
    }
}
